from flask import g, session, jsonify, render_template, request
from application import app, db
from web.models.boke_models import User
import www
import datetime

# 定时任务
from apscheduler.schedulers.background import BackgroundScheduler

# 设置定时器
scheduler = BackgroundScheduler()
scheduler.start()


# 更新用户天数
def update_user_days():
    try:
        user_data = User.query.filter_by(id=session['user_id']).first()
        if user_data:
            user_data.days += 1
            db.session.commit()
    except Exception as e:
        print(e)


# 自定义过滤器
def date(time):
    return time.strftime("%Y-%m-%d")


def my_truncate(s, length, end='...'):
    count = 0
    new = ''
    for c in s:
        new += c
        if ord(c) <= 128:
            count += 0.5

        else:
            count += 1
        if count > length:
            break
    return new + end


app.add_template_filter(date, 'date')
app.add_template_filter(my_truncate, 'my_truncate')


# 钩子函数
@app.before_request
def my_before_request():
    try:
        user_id = int(request.cookies.get('user_id'))
        print(user_id)
        if user_id:
            user = User.query.get(user_id)

            g.user = user
        else:
            g.user = None
    except:
        g.user = None


@app.errorhandler(404)
def page_error(e):
    return render_template('error404.html')


# 上下文处理器
@app.context_processor
def my_context_processor():
    return {'user': g.user}


def main():
    app.run(debug=True)


# with app.app_context():
#     print(app.url_map)
#     print(g.get('user'))
if __name__ == '__main__':
    main()
